package models;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;

import play.data.validation.Constraints.Required;
import play.db.ebean.Model;

@Entity
public class YouUser extends Model {

	@Required @Id
	public long youId;
	
	@OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
	public Set<EmailData> linkedAccounts;
	
	public static Model.Finder<Long, YouUser> find = new Finder<Long, YouUser>(
			Long.class, YouUser.class);
	
	public static YouUser create() {
		YouUser	user = new YouUser();
		user.linkedAccounts = new HashSet<EmailData>();
		user.save();
		return user;
	}
	
	public boolean addAccount(EmailData data) {
		for (EmailData setData : linkedAccounts) {
			if (setData.equals(data)) {
				linkedAccounts.remove(data);
				break;
			}
		}
		
		boolean added = linkedAccounts.add(data);
		this.save();
		return added;
	}
	
	public Set<EmailData> clearLinks() {
		for (EmailData data : linkedAccounts) {
			data.delete();
		}
		Set<EmailData> copy = linkedAccounts;
		linkedAccounts = new HashSet<EmailData>();
		this.save();
		
		return linkedAccounts;
	}
	
	public EmailData unlink(long linkId) {
		EmailData foundData = null;
		for (EmailData data : linkedAccounts) {
			if (data.id == linkId) {
				foundData = data;
				data.delete();
				linkedAccounts.remove(data);
				this.save();
				break;
			}
		}
		
		return foundData;
	}
	
	//TODO change this to enable selection of a specific account
	public GmailData getGmailData() {
		GmailData data = null;
		for (EmailData linkData : linkedAccounts) {
			System.out.println(linkData);
			if (linkData instanceof GmailData) {
				data = (GmailData) linkData;
			}
		}
		return data;
	}

	@Override
	public String toString() {
		return "YouUser [youId=" + youId + ", linkedAccounts=" + linkedAccounts
				+ "]";
	}
}